<template>
	<div class="login">
		<div class="loginBox">
			<div>
				<img style="width: 452px;height: 584px;display: block;" src="../assets/images/loginLeft.png" alt="" />
			</div>
			<div class="loginRight">
				<el-form @submit.prevent ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
					<h3 class="title">聚帮数智化平台</h3>
					<el-form-item prop="username" style="margin-bottom: 25px;">
						<el-input v-model="loginForm.username" type="text" size="large" auto-complete="off"
							placeholder="请输入登录账号" class="pl-10">
							<template #prefix>
								<div class="iconImg">
									<img style="width: 16px;" src="../assets/images/icon1.png" alt="" />
								</div>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item prop="password" style="margin-bottom: 25px;">
						<el-input v-model="loginForm.password" type="password" size="large" auto-complete="off"
							placeholder="请输入密码" @keyup.enter="handleLogin">
							<template #prefix>
								<div class="iconImg">
									<img style="width: 16px;" src="../assets/images/icon2.png" alt="" />
								</div>
							</template>
						</el-input>
					</el-form-item>
					<el-form-item prop="code" v-if="captchaEnabled">
						<el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="请获取手机验证码"
							style="width: 290px;" @keyup.enter="handleLogin">
							<template #prefix>
								<div class="iconImg">
									<img style="width: 16px;" src="../assets/images/icon3.png" alt="" />
								</div>
							</template>
						</el-input>
						<!-- <button class="login-code main-color" :disabled="isCounting" @click="getCaptcha">
					{{ isCounting ? `${countdown}秒` : '获取验证码' }}
				  </button> -->
						<div class="login-code1">
							<img :src="codeUrl" @click="getCode" class="login-code-img" />
						</div>
					</el-form-item>
					<div class="flex col-top row-between mb20 mt25">
						<el-checkbox v-model="loginForm.rememberMe"
							style="color: #677585;font-size: 16px;">记住我</el-checkbox>
						<el-tooltip class="box-item" effect="dark" content="<div>请联系客服重置登录密码</div>"
							placement="top" raw-content>
							<span class="main-color cursor hover-color fs14 mt6">忘记密码？</span>
						</el-tooltip>
						<!-- <router-link class="main-color hover-color fs14 mt6" :to="'/register'">忘记密码？</router-link> -->
					</div>
					<el-form-item style="width:100%;">
						<el-button :loading="loading" size="large" type="defaultBtn" @click.prevent="checkPasswordStrength"
							style="width:100%;box-shadow: 0px 2px 5px  #4DACB1;height: 56px;font-size: 16px;">
							<span v-if="!loading">立即登录</span>
							<span v-else>登 录 中...</span>
						</el-button>
						<!-- <div style="float: right;" v-if="register">
					<router-link class="link-type" :to="'/register'">立即注册</router-link>
				  </div> -->
					</el-form-item>
				</el-form>
				<!--  底部  -->

			</div>
			<div class="el-login-footer">
				<span>©2024 河南聚帮生物药业有限公司 版权所有</span>
			</div>
		</div>
		<!-- 设备更换验证弹窗 -->
		<loginRef ref="loginPop" @handleLogin="handleRefLogin"></loginRef>
	</div>
</template>

<script setup>
	import {
		getCodeImg,
		captchaSms
	} from "@/api/login";
	import Cookies from "js-cookie";
	import {
		encrypt,
		decrypt
	} from "@/utils/jsencrypt";
	import useUserStore from '@/store/modules/user'
	import loginRef from "@/components/loginRef/index.vue"
	const userStore = useUserStore()
	const route = useRoute();
	const router = useRouter();
	const {
		proxy
	} = getCurrentInstance();
	const countdown = ref(60);
	const isCounting = ref(false);
	let timer = null;


	const startCountdown = () => {
		isCounting.value = true;
		timer = setInterval(() => {
			if (countdown.value > 0) {
				countdown.value -= 1;
			} else {
				clearInterval(timer);
				isCounting.value = false;
				countdown.value = 60; // Reset to 60 seconds
			}
		}, 1000);
	};

	const getCaptcha = () => {
		// Replace this with your actual API call to get the captcha
		// console.log('Fetching captcha...');
		const regex = /^1[3-9]\d{9}$/
		if (loginForm.value.username == '') {
			proxy.$modal.msgError("请输入手机号");
			return false;
		} else if (regex.test(loginForm.value.username) == false) {
			proxy.$modal.msgError("手机号格式错误");
			return false;
		}
		captchaSms({
			phone: loginForm.value.username
		}).then(res => {
			startCountdown();
			loginForm.value.uuid = res.uuid;
		})
	};
	// 获取验证码
	function getCaptchaSms() {
		const regex = /^1[3-9]\d{9}$/
		// console.log(regex.test(loginForm.value.username), 'regex.test(loginForm.value.username)')
		if (loginForm.value.username == '') {
			proxy.$modal.msgError("请输入手机号");
			return false;
		} else if (regex.test(loginForm.value.username) == false) {
			proxy.$modal.msgError("手机号格式错误");
			return false;
		}
		captchaSms({
			phone: loginForm.value.username
		}).then(res => {
			loginForm.value.uuid = res.uuid;
		})
	}

	const loginForm = ref({
		username: "",
		password: "",
		rememberMe: false,
		udid: '', //设备码
		code: "",
		uuid: ""
	});

	const loginRules = {
		username: [{
			required: true,
			trigger: "blur",
			message: "请输入您的账号"
		}],
		password: [{
			required: true,
			trigger: "blur",
			message: "请输入您的密码"
		}],
		code: [{
			required: true,
			trigger: "change",
			message: "请输入验证码"
		}]
	};

	function getDeviceInfo() {
		console.log(navigator, 'navigater')
		const browserInfo = `
		  Browser Name: ${navigator.appName}
		  Browser Version: ${navigator.appVersion}
		  User Agent: ${navigator.userAgent}
		  platform:${navigator.platform}
		`;
		// loginForm.value.udid = navigator.userAgent
		console.log(loginForm.value, 'this.loginForm.udid======');
	}
	const codeUrl = ref("");
	const loading = ref(false);
	// 验证码开关
	const captchaEnabled = ref(true);
	// 注册开关
	const register = ref(false);
	const redirect = ref(undefined);


	watch(route, (newRoute) => {
		redirect.value = newRoute.query && newRoute.query.redirect;
	}, {
		immediate: true
	});

	function handleRefLogin(data) {
		console.log(data, 'data')
		if (data) {
			loginForm.value.uuid = data.uuid
			loginForm.value.username = data.username
			loginForm.value.code = data.code
			handleLogin()
		}
	}

	// 密码强度校验
	function checkPasswordStrength(){
		let password=loginForm.value.password;
		if(password==='' || password ===null){
			return true;
		}
		const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).+$/;
		if (!regex.test(password)) {
			proxy.$modal.confirm('密码强度太弱，请抓紧时间修改密码！').then(function () {
				return handleLogin();
			})
		}else{
			return handleLogin();
		}
	}

	function handleLogin() {
		proxy.$refs.loginRef.validate(valid => {
			if (valid) {
				loginForm.value.udid = navigator.userAgent
				console.log(loginForm.value, 'value====')
				loading.value = true;
				// 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
				if (loginForm.value.rememberMe) {
					Cookies.set("username", loginForm.value.username, {
						expires: 30
					});
					Cookies.set("password", encrypt(loginForm.value.password), {
						expires: 30
					});
					Cookies.set("rememberMe", loginForm.value.rememberMe, {
						expires: 30
					});
				} else {
					// 否则移除
					Cookies.remove("username");
					Cookies.remove("password");
					Cookies.remove("rememberMe");
				}
				// 调用action的登录方法
				userStore.login(loginForm.value).then(res => {
					if (res.code == 200) {
						const query = route.query;
						const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
							if (cur !== "redirect") {
								acc[cur] = query[cur];
							}
							return acc;
						}, {});
						location.href = redirect.value || "/"
						router.push({
							path: redirect.value || "/",
							query: otherQueryParams
						});
					} else if (res.code == 10100) {
						//换设备登录
						loading.value = false
						proxy.$refs.loginPop.open()
						return false;
					} else if (res.code == 10200) {
						loading.value = false
						proxy.$modal.msgError("短信欠费");
						return false;
					}
				}).catch(() => {
					loading.value = false;
					// 重新获取验证码
					if (captchaEnabled.value) {
						getCode();
					}
				});
			}
		});
	}

	function getCode() {
		getCodeImg().then(res => {
			captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
			if (captchaEnabled.value) {
				codeUrl.value = "data:image/gif;base64," + res.img;
				loginForm.value.uuid = res.uuid;
			}
		});
	}

	function getCookie() {
		const username = Cookies.get("username");
		const password = Cookies.get("password");
		const rememberMe = Cookies.get("rememberMe");
		loginForm.value = {
			username: username === undefined ? loginForm.value.username : username,
			password: password === undefined ? loginForm.value.password : decrypt(password),
			rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
		};
	}
	getCode();
	getCookie();
</script>

<style lang='scss'>
	.loginBox {
		width: 932px;
		margin: 0 auto;
		display: flex;
		align-items: center;
		background-color: #fff;
		border-radius: 12px;
		-webkit-border-radius: 12px;
		-moz-border-radius: 12px;
		overflow: hidden;
	}

	.login {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		background-image: url("../assets/images/login-background.png");
		background-size: cover;
	}

	.loginRight {
		height: 584px;
		width: 480px;
	}

	.title {
		font-size: 30px;
		margin: 0px auto 60px auto;
		text-align: center;
	}

	.login-form {
		border-radius: 6px;
		background: #ffffff;
		width: 100%;
		padding: 80px 38px 5px;

		.el-input {
			height: 48px;

			input {
				height: 48px;
			}
		}

		.iconImg {
			border-right: 1px solid #DCDFE6;
			height: 100%;
			padding-right: 13px;
			line-height: 4;
			margin-right: 15px;
		}

		.input-icon {
			height: 39px;
			width: 14px;
			margin-left: 0px;
		}
	}

	.login-tip {
		font-size: 13px;
		text-align: center;
		color: #bfbfbf;
	}

	.login-code1 {
		width: 100px;
		height: 48px;
		line-height: 48px;

		img {
			cursor: pointer;
			height: 46px;
			width: 115px;
			vertical-align: middle;
		}
	}

	.login-code {
		width: 100px;
		height: 48px;
		line-height: 48px;
		text-align: center;
		border-radius: 6px;
		float: right;
		border: 1px solid #4DACB1;
		margin-left: 14px;
		cursor: pointer;
		background: #fff;

		img {
			cursor: pointer;
			vertical-align: middle;
		}
	}

	.el-login-footer {
		height: 40px;
		line-height: 40px;
		position: fixed;
		bottom: 0;
		width: 100%;
		text-align: center;
		color: #ccc;
		font-family: Arial;
		font-size: 12px;
		letter-spacing: 1px;
		left: 0;
	}

	.login-code-img {
		height: 40px;
		padding-left: 12px;
	}

	.el-checkbox__input.is-checked .el-checkbox__inner,
	.el-checkbox__input.is-indeterminate .el-checkbox__inner {
		border-color: #4DACB1 !important;
		background-color: #4DACB1 !important;
	}

	.el-checkbox__inner:hover {
		border-color: #677585 !important;
	}

	.el-checkbox__input.is-focus .el-checkbox__inner {
		border-color: #677585 !important;
	}

	.el-checkbox {
		color: #111;
		margin-right: 30px;
		font-size: 16px;
		margin-bottom: 0;
	}

	.el-checkbox__inner {
		width: 16px;
		height: 16px;
	}

	.el-checkbox__input.is-checked+.el-checkbox__label {
		color: #677585 !important;
	}

	.el-checkbox__inner::after {
		left: 4px;
		height: 9px;
		width: 5px;
		top: 0;
	}
</style>